package com.pdd.commons.exception;

import com.pdd.commons.response.ResponseEntity;
import com.pdd.commons.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author:liyangpeng
 * @date:2019/6/5 14:56
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalHandlerException {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity exceptionHandler(Exception e){
        log.error("【pdd博客】程序出现异常:{}",e);
        //其余异常处理
        if(!StringUtils.isEmpty(e.getMessage())){
            return ResponseResult.RETURN_ERROR(e.getMessage());
        }
        return ResponseResult.RETURN_ERROR("服务器异常");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException bindException){
        BindingResult bindingResult=bindException.getBindingResult();
        return ResponseResult.RETURN_ERROR(bindingResult.getAllErrors().get(0).getDefaultMessage());
    }
}
